package com.icinfo.wanandroid.app;

import android.app.Activity;
import android.app.Application;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatDelegate;

import com.icinfo.wanandroid.R;
import com.icinfo.wanandroid.di.component.AppComponent;
import com.icinfo.wanandroid.di.component.DaggerAppComponent;
import com.icinfo.wanandroid.di.module.AppModule;
import com.scwang.smartrefresh.header.DeliveryHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.footer.BallPulseFooter;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;

import javax.inject.Inject;

import dagger.android.AndroidInjector;
import dagger.android.DispatchingAndroidInjector;
import dagger.android.HasActivityInjector;

/**
 * Author: 胡高建
 * Comment: //TODO
 * Date: 2019-07-24 09:28
 */
public class WanAndroidApp extends Application implements HasActivityInjector {
    @Inject
    DispatchingAndroidInjector<Activity> mAndroidInjector;

    private static WanAndroidApp instance;
    private RefWatcher refWatcher;
    public static boolean isFirstRun = true;
    private static volatile AppComponent appComponent;

    //static代码可以防止内存泄漏，全局设置刷新头部和尾部，优先级最低
    static {
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO);
        SmartRefreshLayout.setDefaultRefreshFooterCreator((context, layout) -> {
            //全局设置主体颜色
            layout.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);
            //指定delivery Header,默认是贝塞尔雷达Header
            return (RefreshFooter) new DeliveryHeader(context);
        });
        SmartRefreshLayout.setDefaultRefreshFooterCreator((context, layout) -> {
            //默认是BallPulseFooter
            return new BallPulseFooter(context).setAnimatingColor(ContextCompat.getColor(context, R.color.colorPrimary));
        });
    }

    @Override
    public void onCreate() {
        super.onCreate();
        if (LeakCanary.isInAnalyzerProcess(this)) {
            return;
        }
        refWatcher = LeakCanary.install(this);
        instance = this;
        appComponent = DaggerAppComponent.builder()
                .appModule(new AppModule(instance))
//                .httpModule(new HttpModule())
                .build();

        appComponent.inject(this);
    }

    public static synchronized WanAndroidApp getInstance() {
        return instance;
    }

    @Override
    public AndroidInjector<Activity> activityInjector() {
        return mAndroidInjector;
    }
}
